package cn.hughie.imooc;

import java.util.concurrent.*;

/**
 * @Author yuh
 * @Date Created in 下午10:21 2018/5/25
 * @Description
 */
public class Counter {

    private static final int threadNum = 100;
    private static final int totalClient = 5000;
    //private static int counter = 0;
    private static MyAtomicLong ma = new MyAtomicLong();

    public static void count() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadNum);
        CountDownLatch latch = new CountDownLatch(totalClient);
        for (int i = 0; i < totalClient; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //counter++;
                ma.incremenAndGet();
                latch.countDown();
                semaphore.release();
            });
        }
        latch.await();
        System.out.println(ma.getVolitaleLong());
        executorService.shutdown();
    }

    public static void main(String[] args) throws InterruptedException {
        count();
    }
}
